package com.zqs.config;

import com.zqs.common.CustomException;
import com.zqs.common.R;
import com.zqs.common.RUtil;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public R<Object> customExceptionHandler(CustomException e) {
        return RUtil.fail(e.getMessage());
    }
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public R<Object> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return RUtil.fail(message);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R<Object> exceptionHandler(Exception e) {
        System.err.println(e);
        return RUtil.fail("全局异常捕获>>>" + e.getMessage());
    }
}
